/**
 * SSLUtils.java 19.11.2006
 */
package org.dicr.util.net;

import javax.net.ssl.*;

import org.apache.log4j.*;

/**
 * SSL Utils
 * 
 * @author <A href='http://dicr.org'>Igor A Tarasov</A>
 * @version 061012
 */
public final class SSLUtils {
	protected static final Logger log = Logger.getLogger(SSLUtils.class);

	/**
	 * Disable SSL Sertificates verification
	 * <P>
	 * If sertificate cannot be verified, the exception throing: <B>unable to find valid certification path to requested
	 * target</B>. This fuction disable verification of ssl sertificates and hosts.
	 * </P>
	 */
	public static void disableSertificateVerification() {
		// change SSL to accept untrusted sertificates
		try {
			final SSLContext sc = SSLContext.getInstance("SSL");

			// Create empty HostnameVerifier
			final HostnameVerifier hv = new HostnameVerifier() {
				@Override
                public boolean verify(String urlHostName, SSLSession session) {
					SSLUtils.log.info("Warning: URL Host: " + urlHostName + " vs." + session.getPeerHost());
					return true;
				}
			};

			// Create a trust manager that does not validate certificate chains
			final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
				@Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
					return null;
				}

				@Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
				// NOP
				}

				@Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
				// NOP
				}
			} };

			sc.init(null, trustAllCerts, new java.security.SecureRandom());
			final SSLSocketFactory sslSocketFactory = sc.getSocketFactory();

			HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
			HttpsURLConnection.setDefaultHostnameVerifier(hv);

		} catch (final Exception e) {
			SSLUtils.log.error("Could not create SSLSocketFactory => ", e);
			throw new RuntimeException(e);
		}

	}
}
